import {
  CheckCircleFilled,
  CloseCircleFilled,
  FileExcelFilled,
  FileImageFilled,
  FilePdfFilled,
  FileTextFilled,
  FileWordFilled,
  FileZipFilled
} from '@ant-design/icons';
import { Progress } from 'antd';
import { useMemo } from 'react';
import { getFileSize, getFileType } from '../util';

interface FileViewProps {
  style?: React.CSSProperties;
  data: {
    fileName: string;
    fileSize: number;
    status?: 'done' | 'error' | 'uploading' | 'removed' | 'fail';
    percent?: number;
  };
  isPreview?: boolean;
  handlePreview?: (file: any) => void;
  iconPosition?: 'left' | 'right';
}

const fileIconMap: Record<string, typeof FileWordFilled> = {
  doc: FileWordFilled,
  docx: FileWordFilled,
  xls: FileExcelFilled,
  xlsx: FileExcelFilled,
  pdf: FilePdfFilled,
  zip: FileZipFilled,
  png: FileImageFilled,
  jpg: FileImageFilled,
  jpeg: FileImageFilled,
  gif: FileImageFilled
};
const colorMap = {
  xls: '#53D39C',
  xlsx: '#53D39C',
  pdf: '#FF7878',
  zip: '#FF7878'
};
export function FileView(props: FileViewProps) {
  const { style = {}, handlePreview, isPreview = true, data, iconPosition = 'left' } = props;
  const { fileType, fileSizeStr } = useMemo(() => {
    return {
      fileType: getFileType(data.fileName),
      fileSizeStr: getFileSize(data.fileSize)
    };
  }, [data]);
  const Icon = fileIconMap[fileType] ? fileIconMap[fileType] : FileTextFilled;
  const color = data.status === 'fail' ? '#ff3333' : colorMap[fileType] || '#53B7F4';

  const nodes = [
    <span style={{ marginRight: 5 }} key="file-icon">
      <Icon style={{ fontSize: 20, color, ...style }} />
    </span>,
    <span
      key="file-fileName"
      title={data.fileName}
      className={`attachment-overflow ${isPreview ? 'attachment-preview-file' : ''}`}
      onClick={isPreview ? handlePreview : undefined}
    >
      {data.fileName}
    </span>,
    <span className="attachment-file-size" style={{ color: 'var(--primary-color)' }} key="file-size">
      （{fileSizeStr}）
    </span>
  ];
  if (data.status === 'done') {
    const iconNode = <CheckCircleFilled className="file-status-icon done" key="file-done" />;
    iconPosition === 'left' ? nodes.unshift(iconNode) : nodes.push(iconNode);
  }
  if (data.status === 'fail') {
    const iconNode = <CloseCircleFilled className="file-status-icon failed" key="file-failed" />;
    iconPosition === 'left' ? nodes.unshift(iconNode) : nodes.push(iconNode);
  }
  return (
    <>
      {nodes}
      {data.status === 'uploading' && data.percent !== undefined && (
        <Progress
          percent={data.percent}
          size="small"
          status="active"
          className={`attachment-progress`}
          showInfo={false}
        />
      )}
    </>
  );
}
